from django.shortcuts import render
from django.http import HttpResponse
from .models import USER,Course,Coach,Booking,Teach
from django.db import connection
import psycopg2
from django.db.models import Q

from django.db import transaction
from django.contrib.auth.hashers import check_password, make_password
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Count
import random
import time

from django.views.decorators.http import require_GET
from PIL import Image, ImageDraw, ImageFont
import io

import logging

logger = logging.getLogger('exercise')


@require_GET
def captcha_view(request):
    """生成验证码图片"""
    # 生成随机验证码
    captcha_text = generate_simple_captcha()
    request.session['register_captcha'] = captcha_text
    request.session.set_expiry(300)  # 5分钟过期
    
    # 创建图片
    image = Image.new('RGB', (100, 40), color=(255, 255, 255))
    draw = ImageDraw.Draw(image)
    font = ImageFont.load_default()
    
    # 添加干扰线和噪点
    for i in range(5):
        draw.line([
            (random.randint(0, 100), random.randint(0, 40)),
            (random.randint(0, 100), random.randint(0, 40))
        ], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
    
    for i in range(100):
        draw.point([
            random.randint(0, 100),
            random.randint(0, 40)
        ], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
    
    # 绘制验证码文本
    draw.text((10, 10), captcha_text, fill=(0, 0, 0), font=font)
    
    # 返回图片响应
    buf = io.BytesIO()
    image.save(buf, format='PNG')
    return HttpResponse(buf.getvalue(), content_type='image/png')

# Create your views here.
def ikun(request):
    return render(request, 'try.html')
    # return HttpResponse("Welcome to the Home Page")

def home(request):
    return render(request, 'homepage.html')

def about(request):
    return HttpResponse("This is the About Page")

def login(request):      
    account = request.GET.get('account')
    password = request.GET.get('password')    
    user_type = request.GET.get('option')
    if user_type == '教练':
        try:
            coach  = Coach.objects.get(account = account)
            if check_password(password,make_password(coach.password)):
                login_message = {"account":account,"password":password}
                return render(request,'coach.html',login_message)
            logger.error(f"request: {request},password error")
            return HttpResponse("密码错误!")
        except Coach.DoesNotExist:
            logger.error(f"request: {request},account not exist")
            return HttpResponse("账号不存在！")
    else:                          
        try:
            user = USER.objects.get(account = account)
            if check_password(password,user.password):
                login_message = {"account":account,"password":password}
                return render(request,'user.html',login_message)  
            logger.error(f"request: {request},password error")
            return HttpResponse("密码错误!")
        except USER.DoesNotExist:
            logger.error(f"request: {request},account not exist")
            return HttpResponse("账号不存在！")            

def register(request):
    return render(request,'register.html')

def generate_simple_captcha():
    """生成简单的数字验证码"""
    # return ''.join(random.choices('0123456789', k=4))
    return '1234'
def render_error(msg):
    return f"""
        <html>
            <head> 
                <script>
                    setTimeout(function() {{
                        window.close();
                    }}, 3000);
                </script>
            </head>
            <body>
                <p>{msg}</p>
                <p>3秒后自动返回注册页面...</p>
            </body>
        </html>
    """
def register_success(request):
    # 检查验证码
    user_captcha = request.GET.get('captcha')
    session_captcha = request.session.get('register_captcha', '')
    if not user_captcha or user_captcha != session_captcha:
        error_msg = "验证码错误或已过期！"
        logger.error(f"request: {request},Verification code is incorrect or has expired!")
        return HttpResponse(render_error(error_msg))
    
    # 时间戳检查
    submit_time = request.session.get('register_submit_time', 0)
    current_time = time.time()
    
    if current_time - submit_time < 0:
        error_msg = "提交过于频繁，请稍后再试！"
        logger.error(f"request: {request},Submission too frequent, please try again later!")
        return HttpResponse(render_error(error_msg))
    
    request.session['register_submit_time'] = current_time
    
    required_fields = ['account', 'password', 'password_again', 'name', 'gender', 'age', 'contact', 'address']
    for field in required_fields:
        if not request.GET.get(field):
            error_msg = f"请填写完整的注册信息！{field}不能为空"
            logger.error(f"request: {request},Please fill in all the required registration information!")
            return HttpResponse(f"""
                <html>
                    <head> 
                        <script>
                            setTimeout(function() {{
                                window.close();
                            }}, 3000);
                        </script>
                    </head>
                    <body>
                        <p>{error_msg}</p>
                        <p>3秒后自动返回注册页面...</p>
                    </body>
                </html>
            """)
    # 检查两次密码是否一致
    if request.GET.get('password') != request.GET.get('password_again'):
        logger.error(f"request: {request},Password not the same!")
        return HttpResponse(f"""
            <html>
                <head>
                    <script>
                            setTimeout(function() {{
                                window.close();
                            }}, 3000);
                        </script>
                </head>
                <body>
                    <p>两次输入的密码不一致！</p>
                    <p>3秒后自动返回注册页面...</p>
                </body>
            </html>
        """)
    # 检查账号是否已注册
    account = request.GET.get('account')
    password =request.GET.get('password')
    if USER.objects.filter(account = account).exists():
        logger.error(f"request: {request},Account existed!")
        return HttpResponse(f"""
            <html>
                <head>
                    <script>
                            setTimeout(function() {{
                                window.close();
                            }}, 3000);
                        </script>
                </head>
                <body>
                    <p>该账号已被注册！</p>
                    <p>3秒后自动返回注册页面...</p>
                </body>
            </html>
        """)
    try:
        with transaction.atomic():
            #创建用户
            user = USER.objects.create(
                name = request.GET.get('name'),
                gender = request.GET.get('gender'),
                age = request.GET.get('age'),
                contact = request.GET.get('contact'),
                address = request.GET.get('address'),
                account=account,
                password = make_password(password)
            )   
            with connection.cursor() as cursor:
                try:
                    # 创建数据库用户
                    cursor.execute(f"CREATE USER {account} WITH PASSWORD '{password}'")
                    
                    # 授予基本权限
                    cursor.execute(f"""
                        GRANT SELECT ON 
                            exercise_user,
                            exercise_course, 
                            exercise_booking, 
                            exercise_coach, 
                            exercise_teach 
                        TO {account}
                    """)
                    
                    # 授予booking表的插入和删除权限
                    cursor.execute(f"""
                        GRANT INSERT, DELETE ON exercise_booking TO {account}
                    """)
                    
                except psycopg2.Error as e:
                    # 如果创建失败，回滚Django的用户创建
                    logger.error(f"request: {request},Database user create fail")
                    raise Exception(f"数据库用户创建失败: {str(e)}") 
                    
            return render(request,'register_success.html')
    except Exception as e:
        print(str(e))
        logger.error(f"request: {request},Registe failed!")
        return HttpResponse(f"""
            <html>
                <head>
                    <script>
                            setTimeout(function() {{
                                window.close();
                            }}, 3000);
                        </script>
                </head>
                <body>
                    <p>注册失败: {str(e)}</p>
                    <p>3秒后自动返回注册页面...</p>
                </body>
            </html>
        """)

def search_course(request):
    account = request.GET.get('account')
    password = request.GET.get('password')
    try:
        user = USER.objects.get(account=account)
        if not check_password(password,user.password):
            logger.error(f"request: {request},Not login!")
            return HttpResponse("未登录!")
    except USER.DoesNotExist:
        logger.error(f"request: {request},Not login!")
        return HttpResponse("未登录!")
       
    query = request.GET.get('query', '')
    choose = request.GET.get('选课','')
    cancel = request.GET.get('取消','')
    if choose != '':
            course = Course.objects.get(course_id = request.GET.get('course_id'))
            Booking.objects.get_or_create(user=user,course=course)
    if cancel != '':
            Booking.objects.filter(user=user,course_id=request.GET.get('course_id')).delete()
    
    if query:
        courses = Course.objects.filter(course_name__icontains=query)
    else:
        courses = Course.objects.all()
    course_list = []
    for course in courses:
        teach = Teach.objects.filter(course = course).first()
        coach_name = teach.coach.coach_name if teach else "无"
        # 获取已报名人数
        enrolled = Booking.objects.filter(course=course).count()
        # 检查是否已选
        is_mycourse = Booking.objects.filter(user=user, course=course).exists()
        course_list.append({
            'course_id': course.course_id,
            'course_name': course.course_name,
            'time': course.time,
            'location': course.location,
            'enrolled': enrolled,
            'coach_name': coach_name,
            'is_mycourse': "yes" if is_mycourse else "no"
        })
 
    return render(request,'search_course.html',{'account':account,'password':password,'course_list':course_list})

def user_booking(request):
    account = request.GET.get('account')
    password = request.GET.get('password')
    try:
        user = USER.objects.get(account=account)
        if not check_password(password,user.password):
            logger.error(f"request: {request},Not login!")
            return HttpResponse("未登录!")
    except USER.DoesNotExist:
        logger.error(f"request: {request},Not login!")
        return HttpResponse("未登录!")
    
    choose = request.GET.get('选课','')
    cancel = request.GET.get('取消','')
    if choose != '':
            course = Course.objects.get(course_id = request.GET.get('course_id'))
            Booking.objects.get_or_create(user=user,course=course)
    if cancel != '':
            Booking.objects.filter(user=user,course_id=request.GET.get('course_id')).delete()

    # 获取用户已报名的课程
    booked_courses = Course.objects.filter(booking__user=user)
    course_list = []
    for course in booked_courses:
        teach = Teach.objects.filter(course=course).first()
        coach_name = teach.coach.coach_name if teach else "无"
        
        enrolled = Booking.objects.filter(course=course).count()
        
        course_list.append({
            'course_id': course.course_id,
            'course_name': course.course_name,
            'time': course.time,
            'location': course.location,
            'enrolled': enrolled,
            'coach_name': coach_name,
            'is_mycourse': "yes"
        })
    return render(request,'user_booking.html',{'account':account,'password':password,'course_list':course_list})

def coach_course(request):
    account = request.GET.get('account')
    password = request.GET.get('password')
    try:
        coach = Coach.objects.get(account=account)
        if not check_password(password,make_password(coach.password)):
            logger.error(f"request: {request},Not login!")
            return HttpResponse("未登录!")
    except Coach.DoesNotExist:
        logger.error(f"request: {request},Not login!")
        return HttpResponse("未登录!")
    taught_courses = Course.objects.filter(teach__coach=coach)
    course_list = []
    for course in taught_courses:
        # 获取报名学生
        students = USER.objects.filter(booking__course=course).values_list('name', flat=True)
        student_names = list(students) if students else ["无"]
        
        enrolled = Booking.objects.filter(course=course).count()
        
        for name in student_names:
            course_list.append({
                'course_id': course.course_id,
                'course_name': course.course_name,
                'time': course.time,
                'location': course.location,
                'enrolled': enrolled,
                'user_name': name
            })

    return render(request,'coach_course.html',{'account':account,'password':password,'course_list':course_list})

def create_new_course(request):
    account = request.GET.get('account')
    password = request.GET.get('password')
    try:
        coach = Coach.objects.get(account=account)
        if not check_password(password,make_password(coach.password)):
            logger.error(f"request: {request},Not login!")
            return HttpResponse("未登录!")
    except Coach.DoesNotExist:
        logger.error(f"request: {request},Not login!")
        return HttpResponse("未登录!")

    # 生成新课程ID
    last_course = Course.objects.order_by('-course_id').first()
    new_course_id = 1 if not last_course else last_course.course_id + 1
    course_name = request.GET.get('course_name')
    time = request.GET.get('time')
    location = request.GET.get('location')
    option = request.GET.get('option','')
    if request.method == 'GET' and (not course_name or not time or not location):
        return render(request, 'coachnew.html', {
            'account': account,
            'password':password,
            'course_id': new_course_id
        })
    try:
        with transaction.atomic():
            # 创建新课程
            course = Course.objects.create(
                course_id=new_course_id,
                course_name=course_name,
                time=time,
                location=location
            )
            
            # 关联教练和课程
            Teach.objects.create(coach=coach, course=course)
            return render(request, 'new_success.html', {
                'account': account,
                'password':password,
                'option':option,
                'course_id': new_course_id,
                'course_name': course_name,
                'time': time,
                'location': location
            })
    except Exception as e:
        logger.error(f"request: {request},Creating course failed!")
        return HttpResponse(f"创建课程失败: {str(e)}")

# views.py
from django.views.generic import TemplateView
 
class HomeView(TemplateView):
    template_name = "home.html"  # 指定模板文件路径
 
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = "主页"
        context['message'] = "欢迎访问我们的网站！"
        return context